package com.sky.loveshop.controller;

import cn.hutool.json.JSONUtil;
import com.sky.loveshop.entity.MeiTuanOrder;
import com.sky.loveshop.entity.Result;
import com.sky.loveshop.entity.WxMiniUser;
import com.sky.loveshop.entity.common.PageResult;
import com.sky.loveshop.entity.exception.BizException;
import com.sky.loveshop.entity.exception.BizExceptionEnum;
import com.sky.loveshop.entity.meiTuan.MtOrderDetail;
import com.sky.loveshop.entity.qo.MtOrderInfoQO;
import com.sky.loveshop.entity.vo.DriverOpenDoorVO;
import com.sky.loveshop.entity.vo.WxMiniUserVO;
import com.sky.loveshop.entity.weChat.LogInRequest;
import com.sky.loveshop.entity.weChat.OpenDoorRequest;
import com.sky.loveshop.entity.weChat.ShortLinkRequest;
import com.sky.loveshop.entity.weChat.WXACodeUnLimitRequest;
import com.sky.loveshop.service.MtService;
import com.sky.loveshop.service.WeChatMiniService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

/**
 * @author xcy
 * @version V1.0
 * @description 微信小程序相关
 * @date 2024/10/30 21:04
 */
@Slf4j
@RequestMapping("/weChatMini")
@RestController
public class WeChatMiniController {

    @Autowired
    private WeChatMiniService weChatMiniService;
    @Autowired
    private MtService mtService;

    /**
     * 门禁微信小程序用户登录/注册
     */
    @PostMapping(value = "/wxLoginOrRegister")
    public Result<WxMiniUserVO> wxLoginOrRegister(@RequestBody LogInRequest request) throws BizException {
        log.info("wxLoginOrRegisterParam = {}", JSONUtil.toJsonStr(request));
        if (request.getCode() == null) {
            throw new BizException(BizExceptionEnum.CODE_MUST_NOT_NULL);
        }
        return Result.success(weChatMiniService.wxLoginOrRegister(request));
    }

    /**
     * 门禁微信小程序获取短链
     */
    @PostMapping(value = "/getShortLink")
    public Result<String> getShortLink(@RequestBody ShortLinkRequest request) throws BizException {
        return Result.success(weChatMiniService.getShortLink(request));
    }

    /**
     * 门禁微信小程序码
     */
    @PostMapping(value = "/getWXACodeUnLimit")
    public void getWXACodeUnLimit(@RequestBody WXACodeUnLimitRequest request, HttpServletResponse response) throws BizException, IOException {
        log.info("getWXACodeUnLimitParam = {}", JSONUtil.toJsonStr(request));
        byte[] qrCodeByte = weChatMiniService.getWXACodeUnLimit(request);
        if (qrCodeByte == null || qrCodeByte.length == 0) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, "未获取到二维码");
            return;
        }
        // 设置响应类型和头部
        response.setContentType("image/png");
        response.setHeader("Content-Disposition", "attachment; filename=\"qrcode.png\"");
        response.setContentLength(qrCodeByte.length);
        response.getOutputStream().write(qrCodeByte);
        response.getOutputStream().flush();
    }

    /**
     * 门禁微信小程序用户获取手机号
     */
    @PostMapping(value = "/auth/wxGetUserPhoneNumber")
    public Result<Integer> wxGetUserPhoneNumber(@RequestBody LogInRequest request) throws BizException {
        if (request.getCode() == null) {
            throw new BizException(BizExceptionEnum.CODE_MUST_NOT_NULL);
        }
        if (request.getEncryptedData() == null) {
            throw new BizException(BizExceptionEnum.ENCRYPTED_DATA_MUST_NOT_NULL);
        }
        if (request.getIv() == null) {
            throw new BizException(BizExceptionEnum.IV_MUST_NOT_NULL);
        }
        if (request.getLnt() == null) {
            throw new BizException(BizExceptionEnum.LON_MUST_NOT_NULL);
        }
        if (request.getLat() == null) {
            throw new BizException(BizExceptionEnum.LAT_MUST_NOT_NULL);
        }
        if (request.getShopId() == null) {
            throw new BizException(BizExceptionEnum.SHOP_ID_MUST_NEED);
        }
        return Result.success(weChatMiniService.wxGetUserPhoneNumber(request));
    }

    /**
     * 门禁微信小程序用户获取手机号(新)
     * 获取手机号信息,基础库:2.21.2及以上
     * https://blog.csdn.net/weixin_44295184/article/details/129341624
     */
    @PostMapping(value = "/auth/wxGetNewPhone")
    public Result<WxMiniUser> wxGetNewPhone(@RequestBody LogInRequest request) throws BizException {
        log.info("authWxGetNewPhoneParam = {}", JSONUtil.toJsonStr(request));
        if (request.getCode() == null) {
            throw new BizException(BizExceptionEnum.CODE_MUST_NOT_NULL);
        }
        if (request.getUserId() == null) {
            throw new BizException(BizExceptionEnum.USER_ID_MUST_NOT_NULL);
        }
        return Result.success(weChatMiniService.wxGetNewPhone(request));
    }

    /**
     * 用户线下通过微信小程序开门(用户主动调用)
     * 并校验用户是否在门店附近 校验通过后 进行下发开门指令
     */
    @PostMapping(value = "/auth/userOpenDoor")
    public Result<Integer> userOpenDoor(@RequestBody LogInRequest request) throws BizException {
        log.info("authUserOpenDoorParam = {}", JSONUtil.toJsonStr(request));
        if (request.getUserId() == null) {
            throw new BizException(BizExceptionEnum.USER_ID_MUST_NOT_NULL);
        }
        if (request.getLnt() == null) {
            throw new BizException(BizExceptionEnum.LON_MUST_NOT_NULL);
        }
        if (request.getLat() == null) {
            throw new BizException(BizExceptionEnum.LAT_MUST_NOT_NULL);
        }
        if (request.getShopId() == null) {
            throw new BizException(BizExceptionEnum.SHOP_ID_MUST_NEED);
        }
        return Result.success(weChatMiniService.userOpenDoor(request));
    }

    /**
     * 骑手线下通过微信小程序开门(骑手主动调用)
     * 骑手输入取货码进行开门
     */
    @PostMapping(value = "/auth/driverOpenDoor")
    public Result<DriverOpenDoorVO> driverOpenDoor(@RequestBody OpenDoorRequest request) throws BizException {
        log.info("authDriverOpenDoorParam = {}", JSONUtil.toJsonStr(request));
        if (request.getUserId() == null) {
            throw new BizException(BizExceptionEnum.USER_ID_MUST_NOT_NULL);
        }
        if (request.getOrderCode() == null) {
            throw new BizException(BizExceptionEnum.DRIVER_ORDER_CODE_MUST_NEED);
        }
        if (request.getLnt() == null) {
            throw new BizException(BizExceptionEnum.LON_MUST_NOT_NULL);
        }
        if (request.getLat() == null) {
            throw new BizException(BizExceptionEnum.LAT_MUST_NOT_NULL);
        }
        if (request.getShopId() == null) {
            throw new BizException(BizExceptionEnum.SHOP_ID_MUST_NEED);
        }
        return Result.success(weChatMiniService.driverOpenDoor(request));
    }

    /**
     * 获取当前门店的订单分页(现场核销APP使用)(门禁小程序使用)
     */
    @PostMapping("/auth/listMtOrderPages")
    public Result<PageResult<MeiTuanOrder>> listMtOrderPages(@RequestBody MtOrderInfoQO qo) {
        return Result.page(mtService.listMtOrderPages(qo));
    }

    /**
     * 根据id获取美团订单详情单(门禁小程序使用)
     */
    @GetMapping("/auth/getMtOrderDetailsById")
    public Result<List<MtOrderDetail>> getMtOrderDetailsById(Integer id) {
        log.info("authGetMtOrderDetailsById = {}", id);
        return Result.success(mtService.getMtOrderDetailsById(id));
    }

}
